﻿Imports System.Globalization
Imports System.Runtime.InteropServices

Namespace Converters
    <ValueConversion(GetType(System.Drawing.Bitmap), GetType(ImageSource))> _
    Public Class BitmapToImageSourceConverter
        Implements IValueConverter
        Public Function Convert(ByVal value As Object, ByVal targetType As Type, _
                                ByVal parameter As Object, ByVal culture As CultureInfo) As Object _
            Implements IValueConverter.Convert

            Dim bitmapSource As BitmapSource
            Dim pHbitmap As IntPtr = TryCast(value, System.Drawing.Bitmap).GetHbitmap()

            Try
                bitmapSource = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(pHbitmap, IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions())
            Finally
                DeleteObject(pHbitmap)
            End Try

            Return bitmapSource
        End Function

        Public Function ConvertBack(ByVal value As Object, ByVal targetType As Type, _
                                    ByVal parameter As Object, ByVal culture As CultureInfo) As Object _
            Implements IValueConverter.ConvertBack

            Throw New NotSupportedException()
        End Function

        <DllImport("gdi32.dll", CharSet:=CharSet.Auto, SetLastError:=True)> _
        Private Shared Function DeleteObject(ByVal o As IntPtr) As Integer
        End Function

    End Class
End Namespace
